package com.wushi.lenovo.asia5b.app_ui.login.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.ListPopupWindow;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.mvp.base.BaseMvpActivity;
import com.mvp.base.model.ResultModel;
import com.mvp.common.GlobalValue;
import com.mvp.ui.view.HeadBar;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.login.mvpview.LoginUserActivityView;
import com.wushi.lenovo.asia5b.app_di.login.presenter.LoginUserActivityPresenter;
import com.wushi.lenovo.asia5b.app_di.other.presenter.CodePresenter;
import com.wushi.lenovo.asia5b.app_event.LoginEvent;
import com.wushi.lenovo.asia5b.app_model.profile.CodeModel;
import com.wushi.lenovo.asia5b.app_model.profile.CountryModel;
import com.wushi.lenovo.asia5b.app_ui.profile.activity.CheckEmailActivity;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupListAdapter;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupWindowHelper;
import com.wushi.lenovo.asia5b.app_widget.ErrorTextView;
import com.wushi.lenovo.asia5b.debug.DebugType;
import com.wushi.lenovo.asia5b.debug.activity.DebugActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import timber.log.Timber;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2018/11/29.
 * 账户/短信登录
 */
public class LoginUserActivity extends BaseMvpActivity<LoginUserActivityView, LoginUserActivityPresenter> implements LoginUserActivityView {
    @BindView(R.id.et_login_email)
    EditText et_login_email;
    @BindView(R.id.tv_login_forget)
    TextView tv_login_forget;
    @BindView(R.id.ll_login_email)
    LinearLayout ll_login_email;
    @BindView(R.id.tv_login_countryname)
    TextView tv_login_countryname;
    @BindView(R.id.ll_login_country)
    LinearLayout ll_login_country;
    @BindView(R.id.tv_login_areacode)
    TextView tv_login_areacode;
    @BindView(R.id.et_login_phone)
    EditText et_login_phone;
    @BindView(R.id.et_login_code)
    EditText et_login_code;
    @BindView(R.id.tv_login_getcode)
    TextView tv_login_getcode;
    @BindView(R.id.ll_login_sms)
    LinearLayout ll_login_sms;
    @BindView(R.id.bt_login_submit)
    Button bt_login_submit;
    @BindView(R.id.rb_login_email)
    RadioButton rb_login_email;
    @BindView(R.id.rb_login_sms)
    RadioButton rb_login_sms;
    @BindView(R.id.rg_login_type)
    RadioGroup rg_login_type;
    @BindView(R.id.et_login_pass)
    EditText et_login_pass;
    @BindView(R.id.tv_login_code_error)
    ErrorTextView tv_login_code_error;
    @BindView(R.id.iv_login_eye)
    ImageView iv_login_eye;
    @BindView(R.id.tv_login_email_error)
    ErrorTextView tv_login_email_error;
    @BindView(R.id.tv_login_mobile_error)
    ErrorTextView tv_login_mobile_error;
    @BindView(R.id.tv_login_pass_error)
    ErrorTextView tv_login_pass_error;
    @BindView(R.id.head_loginuser)
    HeadBar head_loginuser;

    private PopupListAdapter<CountryModel> popupListAdapter;
    private ListPopupWindow popupWindow;
    private String email;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_loginuser;
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        email = getIntent().getStringExtra("email");


        initView();

        initData();

        initEvent();
    }

    @Override
    protected void initView() {
        changeLoginType();
        initPopupWindow();

        if (!TextUtils.isEmpty(email)) {
            et_login_email.setText(email);
        }
    }

    private void changeLoginType() {
        ll_login_email.setVisibility(rb_login_email.isChecked() ? View.VISIBLE : View.GONE);
        ll_login_sms.setVisibility(!rb_login_email.isChecked() ? View.VISIBLE : View.GONE);
    }


    private void initPopupWindow() {
        popupListAdapter = new PopupListAdapter<>(this, R.layout.item_popupitem_login_adapter);
        popupWindow = PopupWindowHelper.getListPopupWindow(this, popupListAdapter
                , ll_login_country, ListPopupWindow.WRAP_CONTENT);
    }

    @Override
    protected void initData() {


    }

    private void login() {
        if (rb_login_email.isChecked()) {
            loginUser();
        } else {
            loginSms();
        }
    }

    private void sendCode() {
        String phone = et_login_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            tv_login_mobile_error.setVisibility(View.VISIBLE);
            return;
        }
        if (popupListAdapter.getSelectItem() == null) {
            tv_login_mobile_error.setVisibility(View.VISIBLE);
            return;
        }
        getPresenter().sendCode(phone, popupListAdapter.getSelectItem().getCalling_code(), CodePresenter.CodeType.SMS_LOGIN);
    }

    /**
     * 账号密码登录
     */
    private void loginUser() {
        String email = et_login_email.getText().toString().trim();
        String password = et_login_pass.getText().toString().trim();

        boolean b = false;

        if (TextUtils.isEmpty(email)) {
            tv_login_email_error.setVisibility(View.VISIBLE);
            b = true;
        }
        if (TextUtils.isEmpty(password)) {
            tv_login_pass_error.setText(R.string.filed_is_empty);
            tv_login_pass_error.setVisibility(View.VISIBLE);
            b = true;
        } else {
            if (password.length() < 6) {
                tv_login_pass_error.setText(R.string.pass_notice);
                tv_login_pass_error.setVisibility(View.VISIBLE);
                b = true;
            }
        }
        if (b) {
            return;
        }

        getPresenter().login(email, password);
    }

    /**
     * 短信登录
     */
    private void loginSms() {
        String phone = et_login_phone.getText().toString().trim();
        String code = et_login_code.getText().toString().trim();
        boolean b = false;

        if (TextUtils.isEmpty(phone)) {
            tv_login_mobile_error.setVisibility(View.VISIBLE);
            b = true;
        }
        if (TextUtils.isEmpty(code)) {
            tv_login_code_error.setText(R.string.filed_is_empty);
            tv_login_code_error.setVisibility(View.VISIBLE);
            b = true;
        } else {
            Object tag = et_login_code.getTag();
            if (tag != null && tag instanceof String) {
                String tagCode = (String) tag;
                if (!TextUtils.equals(code, tagCode)) {
                    tv_login_code_error.setText(R.string.invalid_code);
                    tv_login_code_error.setVisibility(View.VISIBLE);
                    b = true;
                }
            }

        }
        if (popupListAdapter.getSelectItem() == null) {
            tv_login_mobile_error.setVisibility(View.VISIBLE);
            b = true;
        }
        if (b) {
            return;
        }
        getPresenter().loginSms(popupListAdapter.getSelectItem().getId() + "", phone, code);
    }

    @Override
    protected void initEvent() {
        if (GlobalValue.isDebug) {
            head_loginuser.setOnClickListener(v->{
                Intent intent=new Intent(LoginUserActivity.this, DebugActivity.class);
                intent.putExtra("type", DebugType.LOGIN);
                startActivity(intent);
            });
        }
        EyeUtils.bindEye(iv_login_eye, et_login_pass);
        tv_login_code_error.setBindEditText(et_login_email);
        tv_login_email_error.setBindEditText(et_login_email);
        tv_login_mobile_error.setBindEditText(et_login_phone);
        tv_login_pass_error.setBindEditText(et_login_pass);
        rg_login_type.setOnCheckedChangeListener((group, checkedId) -> {
            changeLoginType();
            if (checkedId == R.id.rb_login_sms) {
                List<CountryModel> countryModels = popupListAdapter.getmDatas();
                if (countryModels == null || countryModels.size() == 0) {
                    getPresenter().getCountrys();
                }
            }
        });
        popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindow.dismiss();
                popupListAdapter.setSelectPosition(position);
                CountryModel model = popupListAdapter.getSelectItem();
                if (model != null) {
                    tv_login_countryname.setText(model.getName());
                    tv_login_areacode.setText("+" + model.getCalling_code());
                }
            }
        });

    }

    @OnClick({
            R.id.tv_login_forget,
            R.id.ll_login_country,
            R.id.tv_login_getcode,
            R.id.bt_login_submit,
            R.id.tv_loginuser_regiseter
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_login_forget: {//忘记密码
                startActivity(new Intent(this, CheckEmailActivity.class));
            }
            break;
            case R.id.ll_login_country: {//选择国家
                PopupWindowHelper.showPopupWindow(popupWindow);
            }
            break;
            case R.id.tv_login_getcode: {//发送验证码
                et_login_code.setTag("");
                sendCode();
            }
            break;
            case R.id.bt_login_submit: {//登录
                login();
            }
            break;
            case R.id.tv_loginuser_regiseter: {
                startActivity(new Intent(this, RegisterActivity.class));
            }
            break;
        }

    }

    @Override
    public void getCountrysResult(List<CountryModel> countryModels) {
        popupListAdapter.setDatas(countryModels);
    }

    @Override
    public void sendCodeResult(ResultModel<CodeModel> resultModel, CodePresenter.CodeType codeType) {
        if (resultModel != null && resultModel.isSuccess()) {
            ToastUtil.showToast(getString(R.string.otp_send_success));
            getPresenter().interval();
            CodeModel codeModel = resultModel.getData();
            if (codeModel != null) {
                et_login_code.setTag(codeModel.getOTP_code());
                if (GlobalValue.isDebug) {
                    et_login_code.setText(codeModel.getOTP_code());
                }
            }
        }

    }

    @Override
    public void intervalResult(long aLong) {
        Timber.d("--->>>>>>>>---aLong:" + aLong);
        if (aLong == 0) {
            tv_login_getcode.setEnabled(true);
            tv_login_getcode.setText(R.string.chongxinhuoquyanzhengma);
        } else {
            tv_login_getcode.setEnabled(false);
            tv_login_getcode.setText(aLong + "s");
        }
    }

    @Override
    public void loginResult(boolean isLoginSuccess, boolean isEmail) {
        if (isLoginSuccess) {
            finish();
        }else {
            if (isEmail) {
                tv_login_code_error.setVisibility(View.VISIBLE);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onLoginEvent(LoginEvent event) {
        if (event != null) {
            if (TextUtils.equals(event.loginState, CommonConstant.LOGIN_SUCCESS)) {
                d("--->>>>>>>>---登录成功");
                finish();
            }

        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
